<template>
  <a-drawer
    :title="title"
    :maskClosable="true"
    :width="drawerWidth"
    placement="right"
    :closable="true"
    @close="handleCancel"
    :visible="visible"
    style="height: 100%"
  >
    <template slot="title">
      <div style="width: 100%">
        <span>{{ title }}</span>
        <span style="display: inline-block; width: calc(100% - 51px); padding-right: 10px; text-align: right">
          <a-button @click="toggleScreen" icon="appstore" style="height: 20px; width: 20px; border: 0px"></a-button>
        </span>
      </div>
    </template>

    <a-spin :spinning="confirmLoading">
      <a-form-model ref="form" :model="model" :rules="validatorRules2">
        <a-form-item label="函数标识" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="funId">
          <a-input v-model="model.funId" placeholder="请输入函数标识"></a-input>
        </a-form-item>
        <template v-if="funType != '标准值获取'">
          <a-form-item label="起始时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="startDate">
            <a-date-picker
              show-time
              format="YYYY-MM-DD HH:mm:ss"
              v-model="model.startDate"
              v-if="funType == '滚动取值'"
            />
            <a-month-picker show-time format="YYYY-MM" v-model="model.startDate" v-else-if="funType == '当月统计'" />
            <a-date-picker v-model="model.startDate" v-else />
          </a-form-item>
          <a-form-item
            label="取系统时间"
            :labelCol="{
              xs: { span: 24 },
              sm: { span: 0 },
            }"
          >
            <a-row>
              <a-col :span="5"> </a-col>
              <a-col :span="16">
                <a-checkbox v-model="model.isCurrentDate" @change="isCurrentDateOnChange">
                  运算时取系统时间
                </a-checkbox>
              </a-col>
            </a-row>
          </a-form-item>
        </template>
        <template v-if="funType == '日报滚动取值'">
          <a-form-item label="偏移" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-input-group :compact="true" style="display: inline-block; vertical-align: middle">
              <a-select defaultValue="向前" style="width: 100px" v-model="model.deviation">
                <a-select-option value="向前">向前</a-select-option>
                <a-select-option value="向后">向后</a-select-option>
              </a-select>
              <a-input-number :style="{ width: 'calc(50% - 60px)' }" value="1" v-model="model.deviationValue" />
              <div style="height: 32px; line-height: 32px; margin-left: 10px">天</div>
            </a-input-group>
          </a-form-item>
        </template>

        <template v-if="funType == '滚动取值' || funType == '日报取值' || funType == '日报滚动取值'">
          <a-form-item label="滚动" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-input-group :compact="true" style="display: inline-block; vertical-align: middle">
              <a-select defaultValue="向前" style="width: 100px" v-model="model.scroll">
                <a-select-option value="向前">向前</a-select-option>
                <a-select-option value="向后">向后</a-select-option>
              </a-select>
              <a-input-number :style="{ width: 'calc(50% - 60px)' }" value="1" v-model="model.scrollValue" />
              <a-select
                :style="{ width: 'calc(50% - 60px)' }"
                defaultValue="天"
                style="width: 100px"
                v-model="model.scrollUnit"
                v-if="funType == '滚动取值'"
              >
                <a-select-option value="天">天</a-select-option>
                <a-select-option value="时">时</a-select-option>
                <a-select-option value="分">分</a-select-option>
                <a-select-option value="秒">秒</a-select-option>
              </a-select>
              <template v-if="['日报取值', '日报滚动取值'].indexOf(funType) > -1">
                <div style="height: 32px; line-height: 32px; margin-left: 10px">天</div></template
              >
            </a-input-group>
          </a-form-item>
        </template>
        <a-form-model-item label="属性" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input-search
            placeholder="选择属性"
            readOnly
            v-model="model.propName"
            style="width: 220px"
            @search="doSelectDataPropertyList"
          />
        </a-form-model-item>
        <template
          v-if="funType == '滚动取值' || funType == '当日统计' || funType == '当月统计' || funType == '日报滚动取值'"
        >
          <a-form-item label="聚合" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-select defaultValue="平均值" v-model="model.aggregation" style="width: 220px">
              <a-select-option value="平均值">平均值</a-select-option>
              <a-select-option value="方差">方差</a-select-option>
              <a-select-option value="标准值">标准值</a-select-option>
              <a-select-option value="均方根">均方根</a-select-option>
            </a-select>
          </a-form-item>
        </template>
        <template
          v-if="funType == '月初至今' || funType == '季初至今' || funType == '年初至今'"
        >
          <a-form-item label="统计方式" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-select defaultValue="平均值" v-model="model.aggregation" style="width: 220px">
              <a-select-option value="平均值">平均值</a-select-option>
              <a-select-option value="方差">方差</a-select-option>
              <a-select-option value="标准值">标准值</a-select-option>
              <a-select-option value="均方根">均方根</a-select-option>
              <a-select-option value="最大值">最大值</a-select-option>
              <a-select-option value="最小值">最小值</a-select-option>
              <a-select-option value="合计">合计</a-select-option>
            </a-select>
          </a-form-item>
        </template>
      </a-form-model>
    </a-spin>
    <select-data-property-list-modal ref="selectDataPropertyList" @ok="selectDataPropertyOk" />
    <div class="drawer-bootom-button" v-show="!disableSubmit">
      <a-button style="margin-right: 0.8rem" @click="handleCancel">取消</a-button>
      <a-button @click="handleSubmit" type="primary" :loading="confirmLoading">提交</a-button>
    </div>
  </a-drawer>
</template>

<script>
import moment from 'moment'
import Vue from 'vue'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { getAction, postAction, deleteAction } from '@/api/manage'
import { addUser, editUser, queryUserRole, queryall } from '@/api/api'
import { disabledAuthFilter } from '@/utils/authFilter'
import { duplicateCheck } from '@/api/api'
import SelectDataPropertyListModal from '@/views/corp/dataProperty/SelectDataPropertyList'
import dateFormat from '@/components/jeecg/JEasyCron/format-date'

export default {
  name: 'functionAdd',
  components: {
    SelectDataPropertyListModal,
  },
  data() {
    return {
      objId: '', //保存id
      funType: '',
      departDisabled: false, //是否是我的部门调用该页面
      roleDisabled: false, //是否是角色维护调用该页面
      modalWidth: 800,
      drawerWidth: 410,
      modaltoggleFlag: true,
      confirmDirty: false,
      disableSubmit: false,
      dateFormat: 'YYYY-MM-DD',
      validatorRules2: {
        funId: [{ required: true, message: '请输入!' }],
        startDate: [{ required: true, message: '请选择!' }],
      },
      title: '操作',
      visible: false,
      oldFunId: '', //旧标识
      model: {
        funId: '', //
        startDate: '', //起始时间
        isCurrentDate: false, //运算时取系统时间
        deviation: '向前', //偏移
        deviationValue: '1', //偏移值
        deviationUnit: '天', //偏移单位
        scroll: '向前', //滚动
        scrollValue: '1', //滚动值
        scrollUnit: '天', //滚动单位
        property: '', //属性
        propName: '', //属性名称
        aggregation: '平均值', //聚合
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      uploadLoading: false,
      confirmLoading: false,
      headers: {},
      url: {
        fileUpload: window._CONFIG['domianURL'] + '/sys/common/upload',
        userWithDepart: '/sys/user/userDepartList', // 引入为指定用户查看部门信息需要的url
        queryPropertyList: '/dataProperty/dataProperty/list',
        addFormulaDetail: '/userFormula/userFormula/addFormulaDetail',
      },
      propertyOptions: [],
      nextDepartOptions: [],
      propType: '', //默认选择的属性类型
    }
  },
  created() {
    const token = Vue.ls.get(ACCESS_TOKEN)
    this.headers = { 'X-Access-Token': token }
  },
  watch: {
    funType: {
      handler(newValue, oldValue) {
        if (newValue == '日报取值' || newValue == '日报滚动取值'  || newValue == '月初至今' || newValue == '季初至今' || newValue == '年初至今') {
          this.propType = '日报'
        } else if (newValue == '滚动取值' || newValue == '当日统计' || newValue == '当月统计') {
          this.propType = '实时'
        } else {
          this.propType = ''
        }
      },
    },
  },
  computed: {
    uploadAction: function () {
      return this.url.fileUpload
    },
  },
  props: {
    formulaId: {
      type: Number,
    },
  },
  methods: {
    add() {
      this.refresh()
      let that = this
      that.objId = 0
      that.model = Object.assign(
        {},
        {
          startDate: '', //起始时间
          isCurrentDate: false, //运算时取系统时间
          deviation: '向前', //偏移
          deviationValue: '1', //偏移值
          deviationUnit: '天', //偏移单位
          scroll: '向前', //滚动
          scrollValue: '1', //滚动值
          scrollUnit: '天', //滚动单位
          property: '', //属性
          propName: '', //
          aggregation: '平均值', //聚合
        }
      )
      that.resetScreenSize()
      that.visible = true
    },
    edit(record) {
      let that = this
      that.visible = true
      //根据屏幕宽度自适应抽屉宽度
      this.resetScreenSize()
      that.objId = record.id
      that.model = Object.assign({}, JSON.parse(record.funParaJson))
      that.model.id = record.id
      that.model.funId = record.funId

      that.oldFunId = that.model.funId
      if (record.hasOwnProperty('id')) {
      }
      console.log('that.model=', that.model)
    },
    isDisabledAuth(code) {
      return disabledAuthFilter(code)
    },
    //窗口最大化切换
    toggleScreen() {
      if (this.modaltoggleFlag) {
        this.modalWidth = window.innerWidth
      } else {
        this.modalWidth = 800
      }
      this.modaltoggleFlag = !this.modaltoggleFlag
    },
    // 根据屏幕变化,设置抽屉尺寸
    resetScreenSize() {
      let screenWidth = document.body.clientWidth
      if (screenWidth < 410) {
        this.drawerWidth = screenWidth
      } else {
        this.drawerWidth = 410
      }
    },
    refresh() {},
    close() {
      this.$emit('close')
      this.visible = false
      this.disableSubmit = false
      this.nextDepartOptions = []
      this.$refs.form.resetFields()
    },
    handleSubmit() {
      const that = this
      // 触发表单验证
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (!that.model.funId) {
            that.$message.error('请输入函数标识')
            return
          }
          if (!that.model.property) {
            that.$message.error('请选择属性')
            return
          }
          that.confirmLoading = true
          that.model.id = that.objId
          this.model.funType = this.funType
          if (this.model.isCurrentDate) {
            this.model.startDate = ''
          } else {
            if (this.funType == '滚动取值') {
              this.model.startDate = moment(this.model.startDate).format('YYYY-MM-DD HH:mm:ss')
            } else if (this.funType == '当月统计') {
              this.model.startDate = moment(this.model.startDate).format('YYYY-MM')
            } else {
              this.model.startDate = moment(this.model.startDate).format('YYYY-MM-DD')
            }
          }
          console.log('model:', JSON.stringify(this.model))
          that.addFormOk(this.model)
        } else {
          return false
        }
      })
    },
    addFormOk(param) {
      debugger
      var that = this
      var newRow = {
        id: param.id,
        formulaId: this.formulaId,
        funId: param.funId,
        funPara: that.getPara(param),
        funParaJson: JSON.stringify(param),
        funType: param.funType,
      }
      this.saveFunItem(newRow)
    },
    saveFunItem(param) {
      let that = this
      postAction(that.url.addFormulaDetail, param).then((res) => {
        if (res.success) {
          //that.dataSource.push(param)
          that.$message.success('保存成功')
          that.$emit('ok', { oldFunId: that.oldFunId, obj: this.model })
          that.close()
        } else {
          that.$message.warning(res.message)
        }
        that.confirmLoading = false
      })
    },
    getPara(param) {
      var paras = []
      //   startDate: '', //起始时间
      //   isCurrentDate: 0, //运算时取系统时间
      //   deviation: '向前', //偏移
      //   deviationValue: '1', //偏移值
      //   deviationUnit: '天', //偏移单位
      //   scroll: '向前', //滚动
      //   scrollValue: '1', //滚动值
      //   scrollUnit: '天', //滚动单位
      //   property: '', //属性
      //   aggregation: '平均值', //聚合

      switch (param.funType) {
        case '滚动取值':
          if (param.isCurrentDate) {
            paras.push("'" + '当前时间' + "'")
          } else {
            const format = 'yyyy-MM-dd hh:mm:ss'
            var date = dateFormat(param.startDate, format)
            paras.push("'" + date + "'")
          }
          paras.push("'" + param.scroll + "'")
          paras.push(param.scrollValue)
          paras.push("'" + param.scrollUnit + "'")
          paras.push("'" + param.property + "'") //属性
          paras.push("'" + param.aggregation + "'") //聚合
          break
        case '当日统计':
          if (param.isCurrentDate) {
            paras.push("'" + '当前日期' + "'")
          } else {
            const format = 'yyyy-MM-dd'
            var date = dateFormat(param.startDate, format)
            paras.push("'" + date + "'")
          }
          paras.push("'" + param.property + "'") //属性
          paras.push("'" + param.aggregation + "'") //聚合
          break
        case '当月统计':
          if (param.isCurrentDate) {
            paras.push("'" + '当前月份' + "'")
          } else {
            const format = 'yyyy-MM'
            var date = dateFormat(param.startDate, format)
            paras.push("'" + date + "'")
          }
          paras.push("'" + param.property + "'") //属性
          paras.push("'" + param.aggregation + "'") //聚合
          break
        case '标准值获取':
          paras.push("'" + param.property + "'") //属性
          break
        case '日报取值':
          if (param.isCurrentDate) {
            paras.push("'" + '当前日期' + "'")
          } else {
            const format = 'yyyy-MM-dd'
            var date = dateFormat(param.startDate, format)
            paras.push("'" + date + "'")
          }
          paras.push("'" + param.scroll + "'")
          paras.push(param.scrollValue)
          paras.push("'" + param.property + "'") //属性
          break
        case '日报滚动取值':
          if (param.isCurrentDate) {
            paras.push("'" + '当前时间' + "'")
          } else {
            const format = 'yyyy-MM-dd'
            var date = dateFormat(param.startDate, format)
            paras.push("'" + date + "'")
          }
          paras.push("'" + param.deviation + "'")
          paras.push(param.deviationValue)
          paras.push("'" + param.scroll + "'")
          paras.push(param.scrollValue)
          paras.push("'" + param.property + "'") //属性
          paras.push("'" + param.aggregation + "'") //聚合
          break
        default:
          //月、季、年 初至今
           if (param.isCurrentDate) {
            paras.push("'" + '当前日期' + "'")
          } else {
            const format = 'yyyy-MM-dd'
            var date = dateFormat(param.startDate, format)
            paras.push("'" + date + "'")
          } 
          paras.push("'" + param.property + "'") //属性
          paras.push("'" + param.aggregation + "'") //聚合
          break
      }
      return paras.join(',')
    },
    isCurrentDateOnChange(e) {
      if (e.target.checked) {
        this.model.startDate = ''
      }
    },
    handleCancel() {
      this.close()
    },
    doSelectDataPropertyList() {
      this.$refs.selectDataPropertyList.show(this.propType)
    },
    selectDataPropertyOk(obj) {
      this.model.property = obj.propNo
      this.model.propName = obj.propName
    },
  },
}
</script>

<style scoped>
.ant-table-tbody .ant-table-row td {
  padding-top: 10px;
  padding-bottom: 10px;
}

.drawer-bootom-button {
  position: absolute;
  bottom: 0;
  width: 100%;
  border-top: 1px solid #e8e8e8;
  padding: 10px 16px;
  text-align: right;
  left: 0;
  background: #fff;
  border-radius: 0 0 2px 2px;
}

/*【JTC-502】 添加用户两个滚动条*/
/* /deep/ .ant-drawer-body {
  padding-bottom: 53px;
} */
</style>